package processes.nMCounterProcess;

import os.MiniOS;
import os.MiniProcess;
import os.MiniSemaphore;
import os.MiniThread;

public class NMCounterProcessMainThread extends MiniThread
{
	private int N;
	private int bufferSize;
	private Buffer buffer;
	private MiniSemaphore accessCounter; // TODO make them minimutex
	private MiniSemaphore accessBuffer; // TODO make them minimutex

	public NMCounterProcessMainThread(MiniProcess process, String tid)
	{
		super(process, tid);
		this.description = "Main Thread";
		this.accessCounter = new MiniSemaphore(1);
		this.accessBuffer = new MiniSemaphore(1);
	}

	@Override
	public void passThreadArguments(Object[] arguments)
	{
		N = Integer.parseInt((String)arguments[1]);
		bufferSize = Integer.parseInt((String)arguments[2]);
	}

	@Override
	public void run()
	{
		System.out.println("Inside Run");
		buffer = new Buffer(bufferSize, accessBuffer);
		Counter counter = new Counter(accessCounter);
		for (int i = 0; i < N; i++)
		{
			isExcecutionStopped();
			MiniOS.getInstance().createThread(getProcessId(),
					"processes.nMCounterProcess.MCounterThread", new Object[]{counter}).start();
		}
		isExcecutionStopped();
		MiniOS.getInstance().createThread(getProcessId(),
				"processes.nMCounterProcess.MMonitorThread", new Object[]{buffer, counter}).start();
		isExcecutionStopped();
		MiniOS.getInstance().createThread(getProcessId(),
				"processes.nMCounterProcess.MCollectorThread", new Object[]{buffer}).start();
		isExcecutionStopped();
		MiniOS.getInstance().threadTerminated(getProcessId(), tid);
	}

}
